/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2017-06-08 15:14:19
 * Last Modified: 2017-06-09 23:44:42
 * File Name: sso.go
 * Description:
 */

package sso

//package main

import (
	"crypto/tls"
	"fmt"
	"math/rand"
	"time"

	"qkstatis/auth"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	log "github.com/cihub/seelog"
)

var (
	ssoHost string = "sso.app.qkier.com"
)

type SCSessionCheckResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func SCSessionCheck(sessionid string) *SCSessionCheckResp {
	param := map[string]interface{}{
		"sso_key":   "qkieroc",
		"time":      time.Now().Unix(),
		"nonce_str": getRandomString(8),
	}
	data := map[string]interface{}{
		"ticket": sessionid,
	}
	param["sign"] = auth.GetURLSignService().CalcURLSignByMap(param, "f92c6c06226e1c64d7fb685c762ad828")
	reqURL := fmt.Sprintf("https://%s/wback/validate/ticket?sso_key=qkieroc&nonce_str=%s&time=%d&sign=%s", ssoHost, param["nonce_str"], param["time"], param["sign"])
	b := httplib.Post(reqURL)
	b.SetHost(ssoHost)
	b.JSONBody(data)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := &SCSessionCheckResp{}
	if err := b.ToJSON(resp); err != nil {
		log.Errorf("sso 鉴权失败, service page not found!")
		return nil
	}
	return resp
}

func init() {
	ssoHost = beego.AppConfig.DefaultString("sso::sso_host", "sso.app.qkier.com")
}

/*
func main() {
	info := SCSessionCheck("8de06eaab0c842ff9641cf7ef36937b7")
	fmt.Println(info)
}*/

func getRandomString(length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}
